package info.harmonyshive.imagepicker.slice;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import info.harmonyshive.imagepicker.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.render.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.bundle.IBundleManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;
import ohos.utils.IntentConstants;
import ohos.utils.Sequenceable;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

public class MainAbilitySlice extends AbilitySlice {



    public static int FLAG = 0;
    private static CommonDialog builder;
    public Image imgview;
    private static final int REQ_CODE_QUERY_WEATHER = 000000;
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        checkPermission();
        imgview = (Image) findComponentById(ResourceTable.Id_img_profile);

        loadProfileDefault(imgview);
        if(intent.getSequenceableParam("uri")!=null){
            Intent intent1 = new Intent();
            intent1.setUri(intent.getSequenceableParam("uri"));
            PicturePixMap(intent1);
        }



    }
    private void    checkPermission() {
        if (verifySelfPermission("ohos.permission.CAMERA") != IBundleManager.PERMISSION_GRANTED) {
            requestPermissionsFromUser(
                    new String[]{"ohos.permission.CAMERA", "ohos.permission.READ_USER_STORAGE"}, 100);
        }
    }
    private void initWidget() {
        //权限被授予，进行图片选择操作。
        Image imgProfile = (Image) findComponentById(ResourceTable.Id_img_profile);
        Image imgPlus = (Image) findComponentById(ResourceTable.Id_img_plus);
        String[] permissions = {"ohos.permission.CAMERA", "ohos.permission.READ_USER_STORAGE"};

        imgProfile.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                if (verifySelfPermission(permissions[0]) != IBundleManager.PERMISSION_GRANTED) {
                    requestPermissionsFromUser(permissions, 0);
                    FLAG = 1;
                    return;
                }else{
                    showImagePickerOptions();
                }
            }
        });

        imgPlus.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (verifySelfPermission(permissions[0]) != IBundleManager.PERMISSION_GRANTED) {
                    requestPermissionsFromUser(permissions, 0);
                    FLAG = 1;
                    return;
                }else{
                    showImagePickerOptions();
                }

            }
        });

    }

    private void showImagePickerOptions() {
        ImagePickerAbilitySlice.showImagePickerOptions(this, new ImagePickerAbilitySlice.PickerOptionListener() {
            @Override
            public void onTakeCameraSelected() {
//                launchCameraIntent();
            }

            @Override
            public void onChooseGallerySelected() {
                launchGalleryIntent();
            }
        });
    }
    /**
     * 相册选择图片
     */
    private void launchGalleryIntent() {
        Intent intent = new Intent();

        presentForResult(new ImagePickerAbilitySlice(), intent, REQ_CODE_QUERY_WEATHER);

    }
    @Override
    public void onActive() {
        super.onActive();

        initWidget();
        if (FLAG == 1) {
            showSettingsDialog();
        }
    }
    private void showSettingsDialog() {
        builder = new CommonDialog(this);
        DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_options_ok_setting, null, false);
        builder.setContentCustomComponent(layout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.CENTER)
                .show();
        Button ButtonSetting = (Button) layout.findComponentById(ResourceTable.Id_opt_setting);
        Button ButtonCancel = (Button) layout.findComponentById(ResourceTable.Id_opt_cancel);
        ButtonSetting.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                openSettings();
                FLAG = 0;
                builder.destroy();
            }
        });
        ButtonCancel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FLAG = 0;
                builder.destroy();
            }
        });
    }

    // navigating user to app settings
    private void openSettings() {
        Intent intent1 = new Intent();
        intent1.setAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.getUriFromParts("package", getBundleName(), null);
        intent1.setUri(uri);
        startAbilityForResult(intent1, 101);
    }






    /*@Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == REQ_CODE_QUERY_WEATHER) {

            resultData.setUri(resultData.getSequenceableParam("uri"));

            PicturePixMap(resultData);


        }

    }*/

    private void PicturePixMap(Intent intent) {
        //从资源文件加载PixelMap

        DataAbilityHelper helper = DataAbilityHelper.creator(getContext());

        try {
            FileDescriptor fd = helper.openFile(intent.getUri(), "r");
            ImageSource imageSource = ImageSource.create(fd, null);
            //从资源文件加载PixeMap
            PixelMap originMap = imageSource.createPixelmap(null);
            Size originSize = originMap.getImageInfo().size;

            PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();

            options.size = new Size(originSize.width, originSize.height);

            options.pixelFormat = PixelFormat.ARGB_8888;

            options.editable = true;

            //创建结果PixelMap

            PixelMap circlePixelMap = PixelMap.create(options);

            Canvas canvas = new Canvas();

            //将结果PixelMap作为画布背景

            Texture texture = new Texture(circlePixelMap);

            canvas.setTexture(texture);

            Paint paint = new Paint();

            paint.setAntiAlias(true);

            paint.setDither(true);

            PixelMapHolder pixelMapHolder = new PixelMapHolder(PixelMap.create(originMap, options));

            PixelMapShader shader = new PixelMapShader(pixelMapHolder, Shader.TileMode.CLAMP_TILEMODE, Shader.TileMode.CLAMP_TILEMODE);

            paint.setShader(shader, Paint.ShaderType.PIXELMAP_SHADER);

            //生成圆形PixelMap

            canvas.drawCircle(originSize.width * 1.0f / 2, originSize.height * 1.0f / 2, originSize.width * 1.0f / 2, paint);
            intent.setParam("pixMapPicture", circlePixelMap);
            loadProfile(intent);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    protected void loadProfile(Intent intent) {
        Sequenceable pixMapPicture = intent.getSequenceableParam("pixMapPicture");
        Glide.with(getContext())
                .load(pixMapPicture)
                .apply(bitmapTransform(new CircleCrop()))
                .into(imgview);
    }

    private void loadProfileDefault(Image imgview) {
        Glide.with(this)
                .load(ResourceTable.Media_baseline_account_circle_black_48)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)//缓存
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(imgview);
    }


    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
